const { Menu, dialog } = require('electron')
const got = require('got').default
const path = require('path')
const fs = require('fs')
const imageType = require('image-type')
const randomstring = require('randomstring')

const saveImg = (url) => {
  if (url) {
    const contextMenu = Menu.buildFromTemplate([
      {
        label: '图片另存为...',
        click: () => {
          got
            .get(url)
            .then(async (response) => {
              const chunk = Buffer.from(response.rawBody)
              const { ext } = imageType(chunk)
              const filename = randomstring.generate(10) + '.' + ext
              const { filePath, canceled } = await dialog.showSaveDialog({
                title: '图片另存为',
                defaultPath: path.resolve(__dirname, `../public/upload/${filename}`)
              })
              if (!canceled) {
                console.log(filePath)
                fs.writeFileSync(filePath, chunk)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        }
      }
    ])
    contextMenu.popup()
  }
}

module.exports = saveImg
